package com.yzy.fly.boot.tableSharding;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.yzy.fly.FlyEnvMap;
import com.yzy.fly.config.DynamicDataSource;
import com.yzy.fly.config.FlySpringContextUtil;
import com.yzy.fly.function.dynamicDataSource.DynamicDatasourceService;
import com.yzy.fly.function.dynamicDataSource.entity.FlyDataSource;
import com.yzy.fly.mapper.CustomSqlMapper;
import com.yzy.fly.mapper.FlyTableMapper;
import com.yzy.fly.persistence.service.TableService;
import com.yzy.fly.persistence.mapper.TableMapper;
import com.yzy.fly.persistence.util.ProxySqlUtil;
import com.yzy.fly.persistence.util.TableColumnUtil;
import com.yzy.fly.persistence.util.TableNameUtil;
import com.yzy.fly.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
public class FlyTableShardConfigHandler implements TableNameHandler {

    @Override
    public String dynamicTableName(String sql, String tableName) {

        String tmpTableName = tableName;
        if (StringUtils.equalsIgnoreCase("fly_table_shard_config", tmpTableName)) {
            return tmpTableName;
        }

        // 不同数据源存在相同的表 把Mapper调用时的数据源传进来参与查询，后续那个数据源切换就不用了
        String peek = DynamicDataSourceContextHolder.peek();
        String tableSchema = peek;
        FlyTableShardConfigMapper mapper = FlySpringContextUtil.getBean(FlyTableShardConfigMapper.class);
        QueryWrapper<FlyTableShardConfig> queryWrapper = Wrappers.query();
        queryWrapper.eq(FlyTableShardConfig.Fields.tableSchema, tableSchema);
        queryWrapper.eq(FlyTableShardConfig.Fields.tableName, tableName);
        List<FlyTableShardConfig> flyTableShardConfigs = mapper.selectList(queryWrapper);

        if (CollectionUtils.isEmpty(flyTableShardConfigs)) {
            return tmpTableName;
        }

        for (int i = 0; i < flyTableShardConfigs.size(); i++) {
            FlyTableShardConfig flyTableShardConfig = flyTableShardConfigs.get(i);
            String type = flyTableShardConfig.getType();
            String value = flyTableShardConfig.getValue();
            if (StringUtils.equalsIgnoreCase(type, "date")) {
                if (StringUtils.equalsIgnoreCase(value, "week")) {
                    tmpTableName += "_" + DateUtil.getCurrentWeekNum();
                } else if (StringUtils.equalsIgnoreCase(value, "quarter")) {
                    tmpTableName += "_" + ShardUtil.getQuarter(DateUtil.getTodayLocalDate());
                } else if (StringUtils.equalsIgnoreCase(value, "year_ab")) {
                    tmpTableName += "_" + ShardUtil.getOddEvenYear(DateUtil.getTodayLocalDate());
                } else {
                    tmpTableName += "_" + DateUtil.getCurrentDateFormat(value);
                }
            } else if (StringUtils.equalsIgnoreCase(type, "week")) {
                tmpTableName += "_" + DateUtil.getCurrentWeekNum();
            }
        }

        CustomSqlMapper customSqlMapper = FlySpringContextUtil.getBean(CustomSqlMapper.class);
        TableMapper tableMapper = FlySpringContextUtil.getBean(TableMapper.class);
        int existsTableTmp = tableMapper.existsTable(tableSchema, tmpTableName);
        int existsTable = tableMapper.existsTable(tableSchema, tableName);

        if (existsTableTmp == 0) {
            if (1 == existsTable) {
                try {
                    TableService tableService = FlySpringContextUtil.getBean(TableService.class);
                    String createTableSql = tableService.DDL_CreateTable(tableSchema, tableName);
                    if (StringUtils.isNotBlank(createTableSql)) {
                        createTableSql = createTableSql.replace(tableName, tmpTableName);
                        customSqlMapper.ddl(createTableSql);
                        log.info("tableName:{} shardTableName:{} 自动创建成功", tableName, tmpTableName);
                    } else {
                        log.info("tableName:{} shardTableName:{} 自动创建失败 ddl sql is null", tableName, tmpTableName);
                    }

//                    // 动态数据源开关
//                    boolean dynamicEnabled = true;
//                    Properties properties = FlyEnvMap.getInstance().get("applicationProperties");
//                    String dynamicEnabledStr = properties.getProperty("spring.datasource.dynamic.enabled");
//                    if (StringUtils.isNotBlank(dynamicEnabledStr)) {
//                        dynamicEnabled = Boolean.valueOf(dynamicEnabledStr);
//                    }

//                    if (StringUtils.isBlank(tableSchema) || !dynamicEnabled) {
//
//                    } else {
//                        DynamicDatasourceService dynamicDatasourceService = FlySpringContextUtil.getBean(DynamicDatasourceService.class);
////                        if (null != dynamicDatasourceService.flyDataSourceByKey(tableSchema)) {
//                        if (null != dynamicDatasourceService.getCurrentDataSource(tableSchema)) {
//                            try{
//                                DynamicDataSourceContextHolder.push(tableSchema);
//                                createTableSql = tableService.DDL_CreateTable(tableSchema, tableName);
//                                if (StringUtils.isNotBlank(createTableSql)) {
//                                    createTableSql = createTableSql.replace(tableName, tmpTableName);
//                                    customSqlMapper.ddl(createTableSql);
//                                    log.info("tableName:{} shardTableName:{} 自动创建成功", tableName, tmpTableName);
//                                } else {
//                                    log.info("tableName:{} shardTableName:{} 自动创建失败 ddl sql is null", tableName, tmpTableName);
//                                }
//                            } finally {
//                                DynamicDataSourceContextHolder.clear();
//                            }
//                        } else {
//                            log.info("tableName:{} shardTableName:{} 自动创建失败,请检查 dynamic tableSchema:{} 不存在", tableName, tmpTableName, tableSchema);
//                        }
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("tableName:{} shardTableName:{} 自动创建失败,请检查", tableName, tmpTableName);
                }
            } else {
                log.info("tableName:{} shardTableName:{} 不存在,请检查", tableName, existsTableTmp);
            }
        }
//        JdbcTemplate jdbcTemplate = null;
//        if (1 == existsTable || 1 == createTableResult) {
//            logMapper.insert(tableName);
//        }
        return tmpTableName;
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.getCurrentWeekNum());

//        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));    //获取东八区时间
//        int YEAR = calendar.get(Calendar.YEAR);
//        System.out.println("YEAR = " + YEAR);
//        int MONTH = calendar.get(Calendar.MONTH) + 1;
//        System.out.println("MONTH = " + MONTH);
//        //获取当前天数
//        int day = calendar.get(Calendar.DAY_OF_MONTH);
//        System.out.println("day = " + day);
//
//        //获取当前小时
//        int time = calendar.get(Calendar.HOUR_OF_DAY);
//        //获取当前分钟
//        int min = calendar.get(Calendar.MINUTE);
//        //获取当前秒
//        int sec = calendar.get(Calendar.SECOND);
//
//        SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        System.out.println("time = " + time);
    }
}
